package cn.smxy.ln.controller;

import cn.hutool.crypto.SecureUtil;
import cn.smxy.ln.pojo.User;
import cn.smxy.ln.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.smxy.ln.common.lang.Result;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/index")
    public Object index() {
        User user = userService.getById(1);
        return Result.succ(user);
    }

    @PostMapping("/save")
    @ApiOperation("注册")
    @CacheEvict(key = "'user'", value = "list")
    public Object save(@Validated @RequestBody User user) {
        User one = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (one != null)
            return Result.fail("该用户已经存在");
        user.setPassword(SecureUtil.md5(user.getPassword()));
        boolean b = userService.save(user);
        if (b)
            return Result.succ(user);
        else
            return Result.fail("注册失败");
    }

    @GetMapping("/list")
    @HystrixCommand(fallbackMethod = "hystrixGetList")
    @Cacheable(key = "'user'", value = "list", unless = "#result.getData() == null")    //key:缓存数据时使用的 key，可以用它来指定。默认是使用方法参数的值；cacheNames/value：二者选其一即可，指定缓存组件的名字
    public Result queryAll() {
        List<User> list = userService.list();
        if (list == null) {
            throw new RuntimeException("数据库没有user数据，或者信息无法找到");
        }
        return Result.succ(list);
    }

    public Result hystrixGetList() {
        return Result.fail("没有得到对应的信息，数据库user是空的，或者刷新试试");
    }
}
